package com.heima.user.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.LoginDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.user.mapper.ApUserMapper;
import com.heima.utils.AppJwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.Map;


@Service
public class ApUserServiceImpl extends ServiceImpl<ApUserMapper, ApUser> implements ApUserService {
    @Autowired
    private ApUserMapper apUserMapper;

    @Override
    public ResponseResult login(LoginDto dto) {
        String phone = dto.getPhone();
        String password = dto.getPassword();
        //手机号和密码如果为空 返回错误信息
        if (dto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        //手机号和密码如果是null 说明是游客登录
        if (StringUtils.isEmpty(phone) && StringUtils.isEmpty(password)) {
            Map<String, Object> map = new HashMap<>();
            map.put("user", null);
            String token = AppJwtUtil.getToken(0L);
            map.put("token", token);
            return ResponseResult.okResult(map);
        }

        //根据手机号查询用户信息
        LambdaQueryWrapper<ApUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ApUser::getPhone, phone);
        ApUser user = apUserMapper.selectOne(queryWrapper);
        //user为空   用户不存在
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.AP_USER_DATA_NOT_EXIST);
        }
        //获取当前用户保存在数据库中的盐和密码
        String salt = user.getSalt();
        String passwordFromDb = user.getPassword();
        String passwordMd5 = DigestUtils.md5DigestAsHex((password + salt).getBytes());
        if (!passwordFromDb.equals(passwordFromDb)) {
            //如果密码不一致返回错误
            return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
        }
        //出于安全考虑,清空敏感信息
        user.setSalt("");
        user.setPassword("");
        //封装返回给前端的数据
        Map<String, Object> map = new HashMap<>();
        map.put("user", user);
        String token = AppJwtUtil.getToken(user.getId().longValue());
        map.put("token", token);
        return ResponseResult.okResult(map);

    }


}